package com.ruoyi.collect.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.collect.domain.CollectRecipeIngredients;
import com.ruoyi.collect.domain.CollectRecipeSteps;
import com.ruoyi.collect.domain.CollectRecipes;
import com.ruoyi.collect.mapper.CollectRecipeIngredientsMapper;
import com.ruoyi.collect.mapper.CollectRecipeStepsMapper;
import com.ruoyi.collect.mapper.RecipesMapper;
import com.ruoyi.collect.service.IRecipesService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜谱管理Service业务层处理
 * 
 * @author lpt
 * @date 2025-08-14
 */
@Service("collectRecipesServiceImpl")
public class RecipesServiceImpl implements IRecipesService
{
    @Autowired
    private RecipesMapper recipesMapper;

    @Autowired
    private CollectRecipeIngredientsMapper recipeIngredientsMapper;

    @Autowired
    private CollectRecipeStepsMapper recipeStepsMapper;

    /**
     * 查询菜谱管理
     * 
     * @param id 菜谱管理主键
     * @return 菜谱管理
     */
    @Override
    public CollectRecipes selectRecipesById(String id)
    {
        return recipesMapper.selectRecipesById(id);
    }

    /**
     * 查询菜谱管理列表
     * 
     * @param recipes 菜谱管理
     * @return 菜谱管理
     */
    @Override
    public List<CollectRecipes> selectRecipesList(CollectRecipes recipes)
    {
        return recipesMapper.selectRecipesList(recipes);
    }

    /**
     * 新增菜谱管理
     * 
     * @param recipes 菜谱管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRecipes(CollectRecipes recipes)
    {
        // 设置默认值，避免外键约束错误
        if (recipes.getUserId() == null || recipes.getUserId().trim().isEmpty()) {
            // 设置一个默认的用户ID，或者从当前登录用户获取
            // 这里暂时设置为 "1"，实际项目中应该从SecurityContext获取当前用户ID
            recipes.setUserId("1");
        }
        
        // 设置其他默认值
        if (recipes.getStatus() == null) {
            recipes.setStatus(0); // 0-正常状态
        }
        if (recipes.getDel() == null) {
            recipes.setDel(0); // 0-未删除
        }
        if (recipes.getViewCount() == null) {
            recipes.setViewCount("0"); // 初始浏览量为0
        }
        if (recipes.getCollectCount() == null) {
            recipes.setCollectCount("0"); // 初始收藏数为0
        }
        
        recipes.setCreateTime(DateUtils.getNowDate());
        recipesMapper.insertRecipes(recipes);

        // 插入配料数据
        List<Object> materialRows = recipes.getMaterialRows();
        if (materialRows != null && !materialRows.isEmpty()) {
            List<CollectRecipeIngredients> ingredients = new ArrayList<>();
            for (Object obj : materialRows) {
                if (obj instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) obj;
                    CollectRecipeIngredients ingredient = new CollectRecipeIngredients();
                    ingredient.setRecipeId(recipes.getId());
                    ingredient.setIngredientName((String) map.get("materialName"));
//                    ingredient.setQuantity((String) map.get("quantity"));
                    ingredient.setUnit((String) map.get("materialUnit"));
//                    ingredient.setRemark((String) map.get("remark"));
//                    ingredient.setSort((Integer) map.get("sort"));
                    ingredient.setDel(0);
                    ingredients.add(ingredient);
                }
            }
            if (!ingredients.isEmpty()) {
                recipeIngredientsMapper.batchInsertRecipeIngredients(ingredients);
            }
        }

        // 插入步骤数据
        List<Object> stepsData = recipes.getSteps();
        if (stepsData != null && !stepsData.isEmpty()) {
            Integer stepNumber = 1;
            List<CollectRecipeSteps> steps = new ArrayList<>();
            for (Object obj : stepsData) {
                if (obj instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) obj;
                    CollectRecipeSteps step = new CollectRecipeSteps();
                    step.setRecipeId(recipes.getId());
                    step.setStepNumber(stepNumber);
                    step.setStepDescription((String) map.get("description"));
                    step.setStepImageUrl((String) map.get("imagePath"));
//                    step.setStepVideoUrl((String) map.get("stepVideoUrl"));
//                    step.setStepDuration((Integer) map.get("stepDuration"));
//                    step.setRemark((String) map.get("remark"));
//                    step.setSort((Integer) map.get("sort"));
//                    step.setDel(0);
                    steps.add(step);
                }
                stepNumber++;
            }
            if (!steps.isEmpty()) {
                recipeStepsMapper.batchInsertRecipeSteps(steps);
            }
        }

        return 1;
    }

    /**
     * 修改菜谱管理
     * 
     * @param recipes 菜谱管理
     * @return 结果
     */
    @Override
    public int updateRecipes(CollectRecipes recipes)
    {
        return recipesMapper.updateRecipes(recipes);
    }

    /**
     * 批量删除菜谱管理
     * 
     * @param ids 需要删除的菜谱管理主键
     * @return 结果
     */
    @Override
    public int deleteRecipesByIds(String[] ids)
    {
        return recipesMapper.deleteRecipesByIds(ids);
    }

    /**
     * 删除菜谱管理信息
     * 
     * @param id 菜谱管理主键
     * @return 结果
     */
    @Override
    public int deleteRecipesById(String id)
    {
        return recipesMapper.deleteRecipesById(id);
    }



    //---------------------------------------------------------------------------------------------
    @Override
    public CollectRecipes findById(String id) {
        return recipesMapper.selectRecipeById(id);
    }

    @Override
    public Map<String, Object> findByPage(Integer pageNum, Integer pageSize, CollectRecipes recipes) {
        PageHelper.startPage(pageNum,pageSize);
        List<CollectRecipes> list = recipesMapper.select(recipes);
        PageInfo<CollectRecipes> pageInfo = new PageInfo<>(list);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("total", pageInfo.getTotal());
        pageMap.put("pages", pageInfo.getPages());
        pageMap.put("list", pageInfo.getList());
        return pageMap;
    }

    @Override
    public List<CollectRecipes> findBatch() {
        return recipesMapper.select(null);
    }

    @Override
    public int remove(Integer id) {
        return recipesMapper.deleteById(id);
    }

    @Override
    public int removeBatch(Integer[] ids) {
        return recipesMapper.deleteBatch(ids);
    }

    @Override
    public int addid(CollectRecipes domain) {
       return recipesMapper.insert(domain);
    }

    @Override
    public int editid(CollectRecipes domain) {
        return recipesMapper.edit(domain);
    }

}
